package net.java.mediasystems.database.core.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import net.java.mediasystems.database.core.model.MediaItem;
import net.java.mediasystems.database.core.model.MetadataValue;
import net.java.mediasystems.database.core.repository.jpa.MediaItemRepository;
import net.java.mediasystems.database.core.repository.jpa.MetadataValueRepository;
import net.java.mediasystems.database.core.service.MediaItemService;

public class MediaItemServiceImpl implements MediaItemService {

	private static final Logger LOG = LoggerFactory.getLogger(MediaItemServiceImpl.class);
	private static final int SEARCH_MAXIMUM = 50;
	
	private MediaItemRepository mediaItemRepository;
	private MetadataValueRepository metadataValueRepository;
	
	/**
	 * {@inheritDoc}
	 */
	@Transactional
	@Override
	public MediaItem addMediaItem(MediaItem mediaItem) {
		Assert.notNull(mediaItem);
		
		LOG.debug("Adding a new MediaItem.");
		this.mediaItemRepository.save(mediaItem);
		
		if (CollectionUtils.isNotEmpty(mediaItem.getMetadataValues())) {
			LOG.debug("Adding the Metadata to the newly created MediaItem");
			
			for (MetadataValue curMetadataValue : mediaItem.getMetadataValues()) {
				curMetadataValue.setMediaItem(mediaItem);
				this.metadataValueRepository.save(curMetadataValue);
			}
		}
		
		return mediaItem;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Transactional(readOnly = true)
	@Override
	public List<MediaItem> getByTitleLike(String title) {
		Sort.Order sortOrder = new Sort.Order(Direction.ASC, "title").ignoreCase();
		Pageable pageable = new PageRequest(0, SEARCH_MAXIMUM, new Sort(sortOrder));
		
		Page<MediaItem> page = this.mediaItemRepository.findByTitleLikeIgnoreCase("%" + title + "%", pageable);
		return page.getContent();
	}

	public void setMediaItemRepository(MediaItemRepository mediaItemRepository) {
		this.mediaItemRepository = mediaItemRepository;
	}

	public void setMetadataValueRepository(
			MetadataValueRepository metadataValueRepository) {
		this.metadataValueRepository = metadataValueRepository;
	}
}
